/**
 * Copyright 2015 ZhangQu Li
 * <p/>
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 * <p/>
 * http://www.apache.org/licenses/LICENSE-2.0
 * <p/>
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package pers.julio.notepad.PageSwitcher;

import android.content.Context;
import android.os.Bundle;
import android.text.TextUtils;
import android.util.Log;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.Set;

import androidx.fragment.app.Fragment;
import androidx.fragment.app.FragmentManager;
import androidx.fragment.app.FragmentTransaction;
import pers.julio.notepad.PageSwitcher.Base.BaseFragment;
import pers.julio.notepad.PageSwitcher.Bean.PageBean;
import pers.julio.notepad.PageSwitcher.Bean.SwitchBean;

/**
 * ClassName:  PageManager
 * Description: <页面管理类>
 * Author: julio_chan  2020/10/20 11:39
 */
public class PageManager {
    private static final String TAG = PageManager.class.getSimpleName();

    private Map<String, PageBean> mPageMap = new HashMap<String, PageBean>();

    private Context mContext;
    private volatile static PageManager mInstance = null;
    private PageManager() { }
    public static PageManager getInstance() {
        if (mInstance == null) {
            synchronized (PageManager.class) {
                if (mInstance == null) { mInstance = new PageManager(); }
            }
        }
        return mInstance;
    }

    /** 页面 初始化配置*/
    public void init(Context context,String pageJson) {
        this.init(context);
        readConfig(pageJson);
    }
    public void init(Context context) {
        try {
            mContext = context.getApplicationContext();
            readConfig(readFileFromAssets(mContext, "page.json"));
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**  读取 页面配置文件*/
    public void readConfig(String content) {
        JSONArray jsonArray = JSON.parseArray(content);
        Iterator<Object> iterator = jsonArray.iterator();
        JSONObject jsonPage = null;
        String pageName = null;
        String pageClazz = null;
        String pageParams = null;
        while (iterator.hasNext()) {
            jsonPage = (JSONObject) iterator.next();
            pageName = jsonPage.getString("name");
            pageClazz = jsonPage.getString("class");
            pageParams = jsonPage.getString("params");
            if (TextUtils.isEmpty(pageName) || TextUtils.isEmpty(pageClazz)) {
                Log.d(TAG, "page Name is null or pageClass is null");
                return;
            }
            mPageMap.put(pageName, new PageBean(pageName, pageClazz, pageParams));
            Log.d(TAG, "put a page:" + pageName);
        }
        Log.d(TAG, "finished read pages,page size：" + mPageMap.size());
    }

    /** 从assets目录下读取文件*/
    private String readFileFromAssets(Context context, String fileName) {
        String result = "";
        try {
            InputStreamReader inputReader = new InputStreamReader(context.getResources().getAssets().open(fileName));
            BufferedReader bufReader = new BufferedReader(inputReader);
            String line = "";
            while ((line = bufReader.readLine()) != null){
                result += line;
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return result;
    }


    /**手动增新页面*/
    public boolean putPage(String name, Class<? extends BaseFragment> clazz, Map<String, String> params) {
        if (TextUtils.isEmpty(name) || clazz == null) {
            Log.d(TAG, "page Name is null or pageClass is null");
            return false;
        }
        if (mPageMap.containsKey(name)) {
            Log.d(TAG, "page has already put!");
            return false;
        }
        mPageMap.put(name, new PageBean(name, clazz.getName(), buildParams(params)));
        return true;
    }


    // 从hashMap中得到参数的json格式
    private String buildParams(Map<String, String> params) {
        if (params == null) { return ""; }
        String result = JSON.toJSONString(params);
        Log.d(TAG, "params:" + result);
        return result;
    }

    /** 跳转到 Fragement,如果返回栈中有则出栈，否则新建（页面跳转核心函数之一）
     * @param fragmentManager FragmentManager管理类
     * @param pageName 页面别名
     * @param bundle 参数
     * @param animations 动画
     * @return 成功跳转到的fragment
     */
    public Fragment gotoPage(FragmentManager fragmentManager, String pageName, Bundle bundle, int[] animations) {
        Fragment fragment = null;
        if (fragmentManager != null) {
            fragment = fragmentManager.findFragmentByTag(pageName);
        }
        if (fragment != null) {
            fragmentManager.popBackStackImmediate(pageName, 0);
        } else {
            fragment = openPage(fragmentManager, pageName, bundle, animations, true);
        }
        return fragment;
    }

    public Fragment openPage(FragmentManager fragmentManager, SwitchBean page) {
        return openPage(fragmentManager,page.getPageName(),page.getBundle(),page.getAnim(),page.isAddToBackStack());
    }
    /** 打开一个fragemnt(页面跳转核心函数之一)
     * @param fragmentManager FragmentManager管理类
     * @param pageName  页面名
     * @param bundle 参数
     * @param animations 动画类型
     * @param addToBackStack 是否添加到返回栈
     * @return 打开的Fragment对象
     */
    public Fragment openPage(FragmentManager fragmentManager, String pageName, Bundle bundle, int[] animations, boolean addToBackStack) {
        BaseFragment fragment = null;
        try {
            // 0 页面是否配置到系统
            PageBean pageBean = this.mPageMap.get(pageName);
            if (pageBean == null) { return null; }

            // 1 反射获取fragment实例
            if (PageConfig.isOpenAtlas()){
                ClassLoader bundleClassLoader = PageConfig.getBundleClassLoader();
                if(bundleClassLoader==null){ return null; }
                fragment = (BaseFragment) PageConfig.getBundleClassLoader().loadClass(pageBean.getClazz()).newInstance();
            }else{
                fragment = (BaseFragment) Class.forName(pageBean.getClazz()).newInstance();
            }

            // 2 设置fragment 参数
            Bundle pageBundle = getBundle(pageBean);
            if (bundle != null) { pageBundle.putAll(bundle); }
            fragment.setArguments(pageBundle);
            fragment.setPageName(pageName);

            // 3 设置切换动画
            FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
            if (animations != null && animations.length >= 4) {
                fragmentTransaction.setCustomAnimations(animations[0], animations[1], animations[2], animations[3]);
            }

            // 4 页面切换
            Fragment fragmentContainer = fragmentManager.findFragmentById(R.id.fragment_container);
            if (fragmentContainer != null) { fragmentTransaction.hide(fragmentContainer); }
            fragmentTransaction.add(R.id.fragment_container, fragment, pageName);
            if (addToBackStack) { fragmentTransaction.addToBackStack(pageName); }

            fragmentTransaction.commitAllowingStateLoss();
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
        return fragment;
    }



    // 从 page中 提取bundle(pageParams)
    private Bundle getBundle(PageBean pageBean) {
        Bundle bundle = new Bundle();
        String key = null;
        Object value = null;
        if (pageBean != null && pageBean.getParams() != null) {
            JSONObject j = JSON.parseObject(pageBean.getParams());
            if (j != null) {
                Set<String> keySet = j.keySet();
                if (keySet != null) {
                    Iterator<String> ite = keySet.iterator();
                    while (ite.hasNext()) {
                        key = ite.next();
                        value = j.get(key);
                        bundle.putString(key, value.toString());
                    }
                }
            }
        }
        return bundle;
    }

    /**
     * 判断fragment是否位于栈顶
     *
     * @param context 上下文
     * @param fragmentTag fragment的tag
     * @return 是否是栈顶Fragment
     */
   /* public boolean isFragmentTop(Context context, String fragmentTag) {
        if (context != null && context instanceof Switcher) {
            return ((Switcher) context).isFragmentTop(fragmentTag);
        } else {
            BaseActivity topActivity = BaseActivity.getTopActivity();
            if (topActivity != null) {
                return topActivity.isFragmentTop(fragmentTag);
            } else {
                return false;
            }
        }
    }*/
}
